package com.example;

import java.net.URL;
import java.sql.*;
import java.util.*;
import org.json.JSONArray;
import org.json.JSONObject;

import java.io.OutputStream;
import java.net.HttpURLConnection;


public class SendAlert {

    public static void main(String[] args) {
        // 数据库配置
        String dbUrl = "jdbc:sqlite:/app/prometheus/gtid_data/GtidMonitor.db"; // 修改为实际数据库路径
        
        // 执行SQL查询并获取结果
        List<String> problematicSetNames = problematicSetNameQuery(dbUrl);
        if (problematicSetNames.isEmpty()) {
            return;
        }
        StringBuilder description_str = new StringBuilder();
        description_str.append(String.format("已检查121个set，%s个不正常，GTID不一致的set如下：", problematicSetNames.size()));
        List<String> setNames = new ArrayList<>(problematicSetNames);
        description_str.append(String.join(", ", setNames));
        JSONObject alert = new JSONObject();
        JSONObject labels = new JSONObject();
        labels.put("alertname", "gtid不一致");
        labels.put("paasServiceName", "gtid");
        labels.put("severity", "critical");
        alert.put("labels", labels);
        JSONObject annotations = new JSONObject();
        annotations.put("summary", "gtid不一致");
        annotations.put("description", description_str);
        alert.put("annotations", annotations);
        alert.put("status", "firing");

        JSONArray alertsJson = new JSONArray();
        alertsJson.put(alert);
        JSONObject alertObj = new JSONObject();
        alertObj.put("status", "firing");
        alertObj.put("alerts", alertsJson);

        
        // 转换为JSON格式
//        JSONArray jsonArray = new JSONArray(alertsJson);
//        String jsonResponse = jsonArray.toString();
        String jsonResponse = alertObj.toString();

        System.out.println(jsonResponse);
        // 发送到Notification
        sendToNotification(jsonResponse);
    }

    private static List<String> problematicSetNameQuery(String dbUrl) {
        List<String> results = new ArrayList<>();
        String sql = "SELECT g.set_name " +
                     "FROM GTIDINFO g " +
                     "WHERE g.set_name IN (" +
                     "    SELECT set_name " +
                     "    FROM GTIDINFO " +
                     "    GROUP BY set_name " +
                     "    HAVING COUNT(DISTINCT (" +
                     "        LENGTH(COALESCE(gtid_set_str, '')) - " +
                     "        LENGTH(REPLACE(COALESCE(gtid_set_str, ''), ',', ''))" +
                     "    )) > 1" +
                     ") " +
                     "GROUP BY g.set_name";

        try (Connection conn = DriverManager.getConnection(dbUrl);
             Statement stmt = conn.createStatement();
             ResultSet rs = stmt.executeQuery(sql)) {

            while (rs.next()) {
                results.add(rs.getString("set_name"));
            }

        } catch (SQLException e) {
            System.err.println("数据库查询错误:");
            e.printStackTrace();
        }

        return results;
    }

    private static void sendToNotification(String jsonPayload) {
        String notificationUrl = "http://137.64.121.159:9876/api/v1/alert";

        try {
            URL url = new URL(notificationUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
            connection.setDoOutput(true);

            try (OutputStream os = connection.getOutputStream()) {
                byte[] input = jsonPayload.getBytes("UTF-8");
                os.write(input, 0, input.length);
            }

            int responseCode = connection.getResponseCode();
            System.out.println("告警发送状态码: " + responseCode);

        } catch (Exception e) {
            System.err.println("发送告警失败:");
            e.printStackTrace();
        }
    }
}